package com.xyp.mesadmin.md.unit.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyp.mesadmin.md.unit.mapper.MdUnitMeasureMapper;
import com.xyp.mesadmin.md.unit.param.UnitPageParam;
import com.xyp.mesadmin.md.unit.service.MdUnitMeasureService;
import com.xyp.mescommon.entity.md.MdUnitMeasure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/9/24
 * @Solgne 从想做到能做
 * @Desc
 */
@Service
public class MdUnitMeasureServiceImpl implements MdUnitMeasureService {
    @Autowired
    private MdUnitMeasureMapper mdUnitMeasureMapper;

    //查询所有
    @Override
    public PageInfo<MdUnitMeasure> findAll(UnitPageParam unitPageParam) {
        PageHelper.startPage(unitPageParam.getPageNum(), unitPageParam.getPageSize());
        List<MdUnitMeasure> mdUnitMeasures = mdUnitMeasureMapper.selectMdUnitMeasure(unitPageParam.getName());
        PageInfo<MdUnitMeasure> pageInfos = new PageInfo<>(mdUnitMeasures);
        return pageInfos;
    }

    @Override
    public List<MdUnitMeasure> unitList() {
        List<MdUnitMeasure> mdUnitMeasures = mdUnitMeasureMapper.selectMdUnitMeasure(null);
        return mdUnitMeasures;
    }

    @Override
    public MdUnitMeasure findByid(Integer id) {
        MdUnitMeasure mdUnitMeasure = mdUnitMeasureMapper.selectMdUnitMeasureById(id);
        return mdUnitMeasure;
    }

    //删除
    @Override
    public void deleteUnitById(Integer id) {
        mdUnitMeasureMapper.deleteUnit(id);
    }
    //批量删除
    @Override
    public void deleteUnitBatch(List<Integer> ids) {
        mdUnitMeasureMapper.deleteUnitBatch(ids);
    }
    //添加
    @Override
    public void addUnit(MdUnitMeasure mdUnitMeasure) {
        mdUnitMeasureMapper.addUnit(mdUnitMeasure);
    }
    //修改
    @Override
    public void updateUnit(MdUnitMeasure mdUnitMeasure) {
        mdUnitMeasureMapper.updateUnit(mdUnitMeasure);
    }
    //上传文件
    @Override
    public void importUnit(MultipartFile file) {
        /**
         * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
         */
        int BATCH_COUNT = 100;
        /**
         * 缓存的数据
         */
        List<MdUnitMeasure> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        EasyExcel.read(inputStream,MdUnitMeasure.class,new ReadListener<MdUnitMeasure>(){
            //每读取一条数据就调用invoke方法
            @Override
            public void invoke(MdUnitMeasure unit, AnalysisContext analysisContext) {
                System.out.println(unit);
                cachedDataList.add(unit);
                if (cachedDataList.size() == 3){
                    mdUnitMeasureMapper.insertBatch(cachedDataList);
                    cachedDataList.clear();
                }
            }
            //解析完成之后调用的方法
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("解析完毕之后");
                //剩余的数据也需要插入数据库
                if (cachedDataList.size() > 0) {
                    mdUnitMeasureMapper.insertBatch(cachedDataList);
                }
            }
        }).sheet().doRead();
    }
    //导出文件
    @Override
    public void exportExcel(HttpServletResponse response) {
        List<MdUnitMeasure> mdUnitMeasures = mdUnitMeasureMapper.selectMdUnitMeasure(null);
        if (mdUnitMeasures == null){
            throw new RuntimeException("数据不存在");
        }
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = "计量单位数据";
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(),MdUnitMeasure.class).sheet("模板").doWrite(mdUnitMeasures);
        } catch (IOException e) {
        }

    }
}
